package com.Hwadee.eduservice.controller.fron;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.Hwadee.commonutils.JwtUtils;
import com.Hwadee.commonutils.R;
import com.Hwadee.commonutils.vo.CourseOrderVo;
import com.Hwadee.eduservice.client.OrderClient;
import com.Hwadee.eduservice.entity.EduCourse;
import com.Hwadee.eduservice.entity.chapter.ChapterVo;
import com.Hwadee.eduservice.entity.frontvo.CourseFrontVo;
import com.Hwadee.eduservice.entity.frontvo.CourseWebVo;
import com.Hwadee.eduservice.service.EduChapterService;
import com.Hwadee.eduservice.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
//@CrossOrigin
@RequestMapping("/eduservice/coursefront")
public class CourseFrontController {

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private EduChapterService chapterService;

    @Autowired
    private OrderClient orderClient;

    //条件查询带分页查询课程
    @PostMapping("/getFrontCourseList/{current}/{limit}")
    public R getFrontCourseList(@PathVariable("current") long current,
                                @PathVariable("limit") long limit,
                                @RequestBody(required = false) CourseFrontVo courseFrontVo) {
        Page<EduCourse> pageCourse = new Page<>(current, limit);
        Map<String, Object> map = courseService.getFrontCourseList(pageCourse,courseFrontVo);
        //返回分页所有数据
        return R.ok().data(map);
    }


    //课程详情的方法
    @GetMapping("/getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        //根据课程id，编写SQL查询课程信息
        CourseWebVo courseWebVo = courseService.getBaseCourseInfo(courseId);
        //根据课程id查询章节和小节
        List<ChapterVo> chapterVideoList = chapterService.getChapterVideoByCourseId(courseId);
        //根据课程id和用户id支付状态
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        boolean isBuy = false;
        if (!StringUtils.isEmpty(memberId)) {
            isBuy = orderClient.isBuyCourse(courseId, memberId);
        }
        return R.ok().data("courseWebVo", courseWebVo).data("chapterVideoList", chapterVideoList).data("isBuy", isBuy);
    }

     //根据课程id返回课程信息
    @PostMapping("/getCourseInfoOrder/{courseId}")
    public CourseOrderVo getCourseInfoOrder(@PathVariable("courseId") String courseId) {
        CourseOrderVo courseOrderVo = new CourseOrderVo();
        CourseWebVo baseCourseInfo = courseService.getBaseCourseInfo(courseId);
        BeanUtils.copyProperties(baseCourseInfo, courseOrderVo);
        return courseOrderVo;
    }
}
